﻿using System.Linq;

namespace Red.Launcher.Executor
{
    public class Status
    {
        #region Public Types

        public enum Source
        {
            Run,
            Settings,
            Toolkit,
            Engine,
            WorkspaceManager,
            PerforceLogin,

            Count
        }

        #endregion Public Types

        #region Private Data

        private string[] _statuses = new string[ (int)Source.Count ];

        #endregion Private Data

        #region Public Properties

        public bool HasError
        {
            get
            {
                foreach ( string status in _statuses )
                {
                    if ( !string.IsNullOrWhiteSpace( status ) )
                    {
                        return true;
                    }
                }

                return false;
            }
        }

        #endregion Public Properties

        #region Public Methods

        public void Check( bool condition, Source source, string message )
        {
            if ( !condition )
            {
                _statuses[ (int)source ] = message;

                Change?.Invoke();
            }
        }

        public bool HasErrorOnSource( Source source )
        {
            return !string.IsNullOrWhiteSpace( _statuses[ (int)source ] );
        }

        public void Clear()
        {
            for ( int i = 0; i < (int)Source.Count; ++i )
            {
                _statuses[ i ] = null;
            }

            Change?.Invoke();
        }

        public void Clear( Source source )
        {
            _statuses[ (int)source ] = null;

            Change?.Invoke();
        }

        public string this[ Source source ]
        {
            get { return _statuses[ (int)source ]; }
            set { _statuses[ (int)source ] = value; Change?.Invoke(); }
        }

        public override string ToString()
        {
            var s = from status in _statuses where !string.IsNullOrWhiteSpace( status ) select status;
            return string.Join( "\n", s );
        }

        #endregion Public Methods

        #region Events

        public delegate void ChangeDelegate();
        public event ChangeDelegate Change;

        #endregion Events
    }
}
